package com.yuan.springcloud.api.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 自定义zuul过滤器
 * @author YouYuan
 * @version 1.0
 * @date 2020/4/1 11:24
 */
@Component
public class ZuulServerFilter extends ZuulFilter {


    /**
     * 令牌桶限流资源定义
     */
    public static final ConcurrentHashMap<String, RateLimiter> resourceRateLimiter = new ConcurrentHashMap<>();

    static {
        createResourceRateLimiter("order", 10);
    }

    private static void createResourceRateLimiter(String resource, int qps) {

        if (resourceRateLimiter.contains(resource)) {
            resourceRateLimiter.get(resource).setRate(qps);
        } else {
            RateLimiter rateLimiter = RateLimiter.create(qps);
            resourceRateLimiter.putIfAbsent(resource, rateLimiter);
        }
    }

    //使用令牌桶算法限流，每秒钟往桶里放置10个令牌
    //更加全面的限流配置可以使用spring-cloud-zuul-ratelimit框架
    private static final RateLimiter RATE_LIMITER = RateLimiter.create(10);

    /**
     * 过滤器类型
     * pre：请求被路由之前（可以用于身份鉴定）
     * route：负载均衡
     * post：微服务响应之后（可以为响应添加header、收集日志等）
     * error：异常发生时执行
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 指定过滤器的执行顺序，返回值越小，优先级越高
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 当前过滤器是否生效
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 指定过滤器中的业务逻辑
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String requestURI = request.getRequestURI();
        System.out.println("[执行pre过滤器]请求地址：" + requestURI);
        /**
         * 	tryAcquire()：如果获取不到一个令牌,表示流量超时了，没有等待时间
         *  tryAcquire(int permits, long timeout, TimeUnit unit)：获取permits个令牌，如果在指定的时间timeout内，还是没有获取到指定的permits个令牌，那么就返回false
         */
        if (!RATE_LIMITER.tryAcquire()) {
            System.out.println("[请求被限流了]请求地址：" + requestURI);
            RequestContext requestContext = RequestContext.getCurrentContext();
            requestContext.setSendZuulResponse(false);  //不路由
            requestContext.setResponseStatusCode(HttpStatus.FORBIDDEN.value());  //403拒绝访问
        }

        return null;
    }
}
